﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;


public partial class Main_Inventory_PurchaseReturnItem : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Page.IsPostBack == false) //means not do same thing each time do only firsttime
        //{
        if (!IsPostBack)
        {
            binditem();
           // BindDataList();
            strsql = "select LNAME from acc_ledmast where LID='" + Request.QueryString["Lid"].ToString() + "'"; //Bind Supplier Name
            DataTable DT = DU.getdata(strsql);
            if (DT.Rows.Count > 0)
            {
                lblCustomer.Text = DT.Rows[0]["LNAME"].ToString();
            }
            paneldate.Visible = true;
            PanelBillRef.Visible = false;
            panelItem.Visible = false;
            btnSubmit.Visible = false;
        }
        //}  
    }

    protected void BasisofPanelVisiblity()
    {
        if (Radiosearch.SelectedValue == "0")
        {
            paneldate.Visible = true;
            PanelBillRef.Visible = false;
            panelItem.Visible = false;
            
        }
        if (Radiosearch.SelectedValue == "1")
        {
            panelItem.Visible = true;
            paneldate.Visible = false;
            PanelBillRef.Visible = false;
        }
        if (Radiosearch.SelectedValue == "2")
        {
            PanelBillRef.Visible = true;
            panelItem.Visible = false;
            paneldate.Visible = false;

        }
    }

    protected void BindDataList() //getting lid or date and bind format name
    {
        string strDate = string.Format("{0:MM/dd/yyyy}", System.DateTime.Now.ToString());
        if (Request.QueryString["CurDate"] != null)
        {
            string[] str = Request.QueryString["CurDate"].ToString().Split('/');
            strDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        strsql = "select ivr_tran_main.trnid,ivr_tran_main.tfoid,ivr_tranformat.formatname from ivr_tran_main inner join ivr_tranformat on ivr_tran_main.tfoid=ivr_tranformat.tfoid where ivr_tran_main.vendcust_lid= 35 and ivr_tran_main.trantypeid=4 ";
        //strsql = "select ivr_tran_main.trnid,ivr_tran_main.tfoid,ivr_tranformat.formatname from ivr_tran_main inner join ivr_tranformat on ivr_tran_main.tfoid=ivr_tranformat.tfoid where ivr_tran_main.vendcust_lid='" + Request.QueryString["Lid"].ToString() + "' and ivr_tran_main.trantypeid=4 and ivr_tran_main.trndate<='" + strDate + "'";
        DataTable DT = DU.getdata(strsql);
        datalistMain.DataSource = DT;
        datalistMain.DataBind();
    }

    protected void binditem()
    {
        strsql = "select ITMDESC, ITMID from Ivr_Item";
       DataTable dt = DU.getdata(strsql);
       if (dt.Rows.Count > 0)
        {
            DdlItem.DataSource = dt;
            DdlItem.DataTextField = "ITMDESC";
            DdlItem.DataValueField = "ITMID";
            DdlItem.DataBind();
        }
        else
        {
            DdlItem.Items.Clear();
        }
    }

    protected void datalistMain_ItemBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            HiddenField hidTranId = (HiddenField)e.Item.FindControl("hidTranId");
            GridView grdDisplay = (GridView)e.Item.FindControl("grdDisplay");
            SqlParameter[] sparam ={
                                       new SqlParameter("@TRNID",hidTranId.Value.ToString()),
                                       new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                   };
            DataTable DT = DU.getdatausingprocedure("USP_IVR_GetItemDetalisForSalesPurchaseReturn", sparam);
            if (DT.Rows.Count > 0)
            {
                grdDisplay.DataSource = DT;
                grdDisplay.DataBind();
            }
        }            
    }

    protected void grdDisplay_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView grdDisplay = (GridView)sender;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox chkItem = (CheckBox)e.Row.Cells[3].FindControl("chkItem");
            HiddenField hidItemId = (HiddenField)e.Row.Cells[3].FindControl("hidItemId");
            chkItem.Attributes.Add("onclick", "return SelectAll(this.id,'" + hidItemId.ClientID + "');");
            HiddenField hidTrnItemId = (HiddenField)e.Row.Cells[3].FindControl("hidTrnItemId");//onclick="return SelectAll(this.id);"
            if (Session["DTPurchaseReturn"] != null)
            {
                DataTable DTCheck = (DataTable)Session["DTPurchaseReturn"];
                if (DTCheck.Rows.Count > 0)
                {
                    for (int i = 0; i < DTCheck.Rows.Count; i++)
                    {
                        if (hidTrnItemId.Value.ToString() == DTCheck.Rows[i]["TITID"].ToString())
                        {
                            chkItem.Checked = true;
                        }
                    }
                }
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
       
        GetCheckedbox();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "DisplayData();", true);
    }

    protected void GetCheckedbox()
    {
        DataTable DTMain = new DataTable();
        DTMain.Columns.Add("TITID");
        DTMain.Columns.Add("ItemId");
        DTMain.Columns.Add("ItemCode");
        DTMain.Columns.Add("ItemName");
        DTMain.Columns.Add("UOMID");
        DTMain.Columns.Add("UomSymbol");
        DTMain.Columns.Add("Rate");
        DTMain.Columns.Add("Qty");
        for (int i = 0; i < datalistMain.Items.Count; i++)
        {
            GridView grdDisplay = (GridView)datalistMain.Items[i].FindControl("grdDisplay");
            for (int j = 0; j < grdDisplay.Rows.Count; j++)
            {
                CheckBox chkItem = (CheckBox)grdDisplay.Rows[j].Cells[3].FindControl("chkItem");
                HiddenField hidItemId = (HiddenField)grdDisplay.Rows[j].Cells[3].FindControl("hidItemId");
                HiddenField hidUomId = (HiddenField)grdDisplay.Rows[j].Cells[3].FindControl("hidUomId");
                HiddenField hidUomSymbol = (HiddenField)grdDisplay.Rows[j].Cells[3].FindControl("hidUomSymbol");
                HiddenField hidTrnItemId = (HiddenField)grdDisplay.Rows[j].Cells[3].FindControl("hidTrnItemId");
                if (chkItem.Checked == true)
                {
                    DataRow DRMain = DTMain.NewRow();
                    DRMain["TITID"] = hidTrnItemId.Value.ToString();
                    DRMain["ItemId"] = hidItemId.Value.ToString();
                    DRMain["ItemCode"] = grdDisplay.Rows[j].Cells[4].Text;
                    DRMain["ItemName"] = grdDisplay.Rows[j].Cells[5].Text;
                    DRMain["UOMID"] = hidUomId.Value.ToString();
                    DRMain["UomSymbol"] = hidUomSymbol.Value.ToString();
                    DRMain["Rate"] = grdDisplay.Rows[j].Cells[6].Text;
                    DRMain["Qty"] = grdDisplay.Rows[j].Cells[7].Text;
                    DTMain.Rows.Add(DRMain);
                }
            }
        }
        Session["DTPurchaseReturn"] = DTMain;
    }

    public static void MergeRows(GridView gridView)
    {
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow row = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 0; i < 3; i++)
            {
                if (row.Cells[i].Text == previousRow.Cells[i].Text)
                {
                    row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;
                }
            }
        }
    }

    protected void grdDisplay_PreRender(object sender, EventArgs e)
    {
        for (int i = 0; i < datalistMain.Items.Count; i++)
        {
            GridView grdDisplay = (GridView)datalistMain.Items[i].FindControl("grdDisplay");
            MergeRows(grdDisplay);
        }
    }

    protected void BindDataListBasedOnTwoDate()
    {
        string strFromDate = string.Empty;
        string strToDate = string.Empty;
        if (txtDateFrom.Text != string.Empty)
        {
            string[] str = txtDateFrom.Text.ToString().Split('/');
            strFromDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        if (txtDateTo.Text != string.Empty)
        {
            string[] str = txtDateTo.Text.ToString().Split('/');
            strToDate = str[1] + "/" + str[0] + "/" + str[2];
        }
        strsql = "select ivr_tran_main.trnid,ivr_tran_main.tfoid,ivr_tranformat.formatname from ivr_tran_main inner join ivr_tranformat on ivr_tran_main.tfoid=ivr_tranformat.tfoid where ivr_tran_main.vendcust_lid='" + Request.QueryString["Lid"].ToString() + "' and ivr_tran_main.trantypeid=4 and ivr_tran_main.trndate between '" + strFromDate + "' and '" + strToDate + "'";
        DataTable DT = DU.getdata(strsql);
        datalistMain.DataSource = DT;
        datalistMain.DataBind();

        if (DT.Rows.Count > 0)
        {
            btnSubmit.Visible = true;
        }
    }

    protected void BindBasisofBillNo()
    {
        strsql = "select ivr_tran_main.trnid,ivr_tran_main.tfoid,ivr_tranformat.formatname from ivr_tran_main inner join ivr_tranformat on ivr_tran_main.tfoid=ivr_tranformat.tfoid where ivr_tran_main.vendcust_lid=35 and ivr_tran_main.trantypeid=4 and ivr_tran_main.Invoiceno = '" + TxtBillRef.Text.ToString()+"'";
        DataTable dt = DU.getdata(strsql);
        if (dt.Rows.Count > 0)
        {
            datalistMain.DataSource = dt;
            datalistMain.DataBind();
        }
    }

    protected void BindBasisOfItem()
    { 
            ListItemCollection _listcollection = new ListItemCollection();
            _listcollection.Clear();
            string listvalue = "";
            foreach (ListItem _item in DdlItemrepresent.Items)
            {
                    if (_item.Selected)
                    {
                        _listcollection.Add(_item);
                        listvalue += _item.Value + ",";
                    }
            }
        listvalue =  listvalue.Substring(0,listvalue.Length-1);

        for (int i = 0; i < _listcollection.Count; i++)
        {
            //lblMsg +="<br/>"+ _listcollection[i].Value.ToString();
            strsql = "select ivr_tran_main.trnid,ivr_tran_main.tfoid,ivr_tranformat.formatname from ivr_tran_main inner join ivr_tranformat on ivr_tran_main.tfoid=ivr_tranformat.tfoid where ivr_tran_main.vendcust_lid=35 and ivr_tran_main.trantypeid=4 and ivr_tran_main.trnid in (select trnid from ivr_tran_item where itmid in (" + listvalue + ")) ";

            DataTable dt = DU.getdata(strsql);
            if (dt.Rows.Count > 0)
            {
                datalistMain.DataSource = dt;
                datalistMain.DataBind();
                btnSubmit.Visible = true;
            }

            else
            {
                //lblMsg.Text =  
            }
        }
    }

    protected void btnShow_Click(object sender, EventArgs e)
    {
        if (Radiosearch.SelectedValue == "0")
        {
            Panelview.Visible = true;
            BindDataListBasedOnTwoDate();
        }
        if (Radiosearch.SelectedValue == "1")
        {
                Panelview.Visible = true;
                BindBasisOfItem();
        }
        if (Radiosearch.SelectedValue == "2")
        {
            Panelview.Visible = true;
            BindBasisofBillNo();
        }
        //BindDataListBasedOnTwoDate();
    }

    protected void Radiosearch_SelectedIndexChanged(object sender, EventArgs e)
    {
        BasisofPanelVisiblity();
    }

    protected void BtnNext_Click(object sender, EventArgs e)
    {
        try
        {
            //DdlItemrepresent.Items.Add(DdlItem.SelectedItem);
            //DdlItem.Items.Remove(DdlItem.SelectedItem);

            ListItemCollection _listcollection = new ListItemCollection();

            foreach (ListItem _item in DdlItem.Items)
            {
                if (_item.Selected)
                {
                    _listcollection.Add(_item);

                }
            }

            for (int i = 0; i < _listcollection.Count; i++)
            {
                DdlItem.Items.Remove(_listcollection[i]);
                DdlItemrepresent.Items.Add(_listcollection[i]);
            }

            _listcollection = null;

        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
            
    }    

    protected void BtnPrevious_Click(object sender, EventArgs e)
    {
        try
        {
            //DdlItem.Items.Add(DdlItemrepresent.SelectedItem);
            //DdlItemrepresent.Items.Remove(DdlItemrepresent.SelectedItem); 

            ListItemCollection _listcollection = new ListItemCollection();

            foreach (ListItem _item in DdlItemrepresent.Items)
            {
                if (_item.Selected)
                {
                    _listcollection.Add(_item);
                }
            }

            for (int i = 0; i < _listcollection.Count; i++)
            {
                DdlItemrepresent.Items.Remove(_listcollection[i]);
                DdlItem.Items.Add(_listcollection[i]);
            }

            _listcollection = null;
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
   }

    

}

  
        